//
//  AppDelegate.m
//  BosidengIphone
//
//  Created by  on 11-12-25.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "AppLoadingViewController.h"
#import "MainViewController.h"
#import "IndexViewController.h"
#import "ProductData.h"
#import "Language.h"

static NSString *SERVER_URL = @"http://app.bosideng.com";

static NSString *CACHE_PATH = @"temp";

static NSString *language = @"jt";

static NSMutableDictionary *rootConfig;

@implementation AppDelegate

@synthesize window = _window;


//获取当前运行程序目录下文件的路径
+ (NSString *)getDocumentFilePath:(NSString *)fileName {
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	if (!documentsDirectory) {
		NSLog(@"Documents directory not found!");
		return nil;
	}
	if (fileName) {
		documentsDirectory = [documentsDirectory stringByAppendingPathComponent:fileName];
	}
	return documentsDirectory;
}

//获取当前运行程序目录下Cache的路径
+ (NSString *) getCacheFilePath:(NSString *)fileName {
	NSString *documentsDirectory = [AppDelegate getDocumentFilePath:CACHE_PATH];
    if (![AppDelegate checkDirExist:documentsDirectory]) {
        [AppDelegate createDir:documentsDirectory];
    }
	if (fileName) {
		documentsDirectory = [documentsDirectory stringByAppendingPathComponent:fileName];
	}
	return documentsDirectory;
}

//获取当前应用程序中文件的路径
+ (NSString *)bundlePath:(NSString *)fileName {
	return [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:fileName];
}

//判断目录是否存在
+ (BOOL)checkDirExist:(NSString *)director {
    NSFileManager *fm = [NSFileManager defaultManager];  
    BOOL isDir;  
    if ([fm fileExistsAtPath:director isDirectory:&isDir]) {  
         return YES;
    } 
    return NO;
}

//创建目录
+ (void)createDir:(NSString *)director {
    NSError *error;
    NSFileManager *fm = [NSFileManager defaultManager];  
    BOOL isDir;  
    if (![fm fileExistsAtPath:director isDirectory:&isDir]) {  
        if (![fm createDirectoryAtPath:director withIntermediateDirectories:YES attributes:nil error:&error]) {   
            [NSException raise:@"Exception" format:[error localizedDescription], nil];  
        }  
    } else if (!isDir) {  
        [NSException raise:@"Exception" format:@"Failed to create directory at %@, because there is a file already.", director];  
    }  
}

//判断文件是否存在
+ (BOOL)checkFileExist:(NSString *)filePath {
	NSFileManager *fm = [NSFileManager defaultManager];
	BOOL fileExist = [fm fileExistsAtPath:filePath];
	//[fm release];
	return fileExist;
}

//删除文件和文件夹
+ (BOOL)deleteFile:(NSString *)filePath {
	NSError *error;
	NSFileManager *fm = [NSFileManager defaultManager];
	if ([fm fileExistsAtPath:filePath]) {
		if (![fm removeItemAtPath:filePath error:&error]) {
			NSLog(@"Delete File: %@ failed .Error is %@", filePath, [error localizedDescription]);
			return NO;
		}
	}
	//[fm release];
	return YES;
}

+ (NSString *)getCacheFilePathByUrl:(NSString *)url {
    NSString *name = [url lastPathComponent];
    NSString *path = [AppDelegate getCacheFilePath:name];
    return path;
}

+ (void)setLanguage:(NSString *)str {
    Language *language = (Language *)[Language findFirstByCriteria:@"WHERE row_id=1"];
    if (language == nil) {
        language = [[[Language alloc] init] autorelease];
        language.rowId = 1;
    }
    language.selectLanguage = str;
    [language save];
}

+ (NSString *)getLanguage {
    Language *language = (Language *)[Language findFirstByCriteria:@"WHERE row_id=1"];
    if (language == nil) {
        [AppDelegate setLanguage:@"jt"];
        return @"jt";
    }
    return language.selectLanguage;
}

+ (CustomData *)getCustom {
    CustomData *custom = (CustomData *)[CustomData findFirstByCriteria:@"WHERE row_id=1"];
    return custom;
}

+ (void)setBackImagePath:(NSString *)str {
    Language *language = (Language *)[Language findFirstByCriteria:@"WHERE row_id=1"];
    if (language == nil) {
        language = [[[Language alloc] init] autorelease];
        language.rowId = 1;
    }
    language.backImagePath = str;
    [language save];
}

+ (NSString *)getBackImagePath {
    Language *language = (Language *)[Language findFirstByCriteria:@"WHERE row_id=1"];
    if (language == nil) {
        return @"";
    }
    return language.backImagePath;
}

+ (void)cleanLanguageStringBuffer {
    if (rootConfig == nil) {
		rootConfig = [[NSMutableDictionary alloc] init];
	}
    [rootConfig removeAllObjects];
}

+ (NSString *)getLanguageString:(NSString *)key {
	
	if (rootConfig == nil) {
		rootConfig = [[NSMutableDictionary alloc] init];
	}
    
    //NSString *defaultName = @"";
	NSString *language = [AppDelegate getLanguage];
	//if ([@"en" isEqualToString:language]) {
    //    defaultName = @"en";
    //} else if ([@"ft" isEqualToString:language]) {
    //    defaultName = @"zh_TW";
    //} else {
    //    defaultName = @"zh_CN";
    //}
	//NSString *fileName = [NSString stringWithFormat:@"String_%@", defaultName];
    NSString *fileName = [NSString stringWithFormat:@"language_%@.xml", language];
	NSDictionary *stringConfig = [rootConfig objectForKey:fileName];
	if (stringConfig == nil) {
		//NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
        NSString *path = [AppDelegate getCacheFilePath:fileName];
        //NSLog(@"language path:%@", path);
		stringConfig = [[NSDictionary alloc] initWithContentsOfFile:path];
		[rootConfig setValue:stringConfig forKey:fileName];
		[stringConfig release];
	}
    NSString *message = [stringConfig objectForKey:key];
    if (message == nil) {
        return key;
    }
	return message;
}

- (void)dealloc
{
    [rootConfig release];
    rootConfig = nil;
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
    NSString *currentLanguage = [languages objectAtIndex:0];
    //NSLog(@"currentLanguage=%@", currentLanguage);
    if ([@"zh-Hans" isEqualToString:currentLanguage]) {
        [AppDelegate setLanguage:@"jt"];
    } else if ([@"zh-Hant" isEqualToString:currentLanguage]) {
        [AppDelegate setLanguage:@"ft"];
    } else {
        [AppDelegate setLanguage:@"en"];
    }
    
    AppLoadingViewController *viewController = [[AppLoadingViewController alloc]initWithNibName:@"AppLoadingViewController" bundle:nil];
    self.window.rootViewController = viewController;
    [viewController release];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

- (void)showMainView:(UIViewController *)contentViewController {
    MainViewController *viewController = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
    viewController.contentViewController = contentViewController;
    self.window.rootViewController = viewController;
    [viewController release];
}

- (void)showIndexView {
    IndexViewController *viewController = [[IndexViewController alloc]initWithNibName:@"IndexViewController" bundle:nil];
    viewController.products = [ProductData getRecommendItems];
    self.window.rootViewController = viewController;
    [viewController release];
}

- (void)reloadApp {
    AppLoadingViewController *viewController = [[AppLoadingViewController alloc]initWithNibName:@"AppLoadingViewController" bundle:nil];
    self.window.rootViewController = viewController;
    [viewController release];
}

+ (NSString *)serviceUrl {
    return SERVER_URL;
}

@end
